package com.photography.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.photography.common.Result;
import com.photography.entity.Product;
import com.photography.entity.ProductReview;
import com.photography.exception.ErrorCode;
import com.photography.mapper.ProductMapper;
import com.photography.mapper.ProductReviewsMapper;
import com.photography.service.ProductService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Resource
    private ProductReviewsMapper productReviewsMapper;


    /**
     * 新增产品
     *
     * @param product 产品信息
     * @return 结果
     */
    @Override
    public Result addProduct(Product product) {
        // 验证必填字段
        if (!StringUtils.hasText(product.getProductName())) {
            return Result.error("产品名称不为空");
        }
        if (!StringUtils.hasText(product.getDescription())) {
            return Result.error("产品描述不能为空");
        }
        if (product.getPrice() == null || product.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("产品价格必须大于0");
        }
        if (!StringUtils.hasText(product.getCategory())) {
            return Result.error("产品分类不能为空");
        }

        // 设置创建和更新时间
        Date now = new Date();
        product.setCreateTime(now);
        product.setUpdateTime(now);

        boolean result = this.save(product);

        if (result) {
            return Result.success(product, "添加产品成功");
        } else {
            return Result.error("添加产品失败");
        }
    }

    /**
     * 删除产品
     *
     * @param productId 产品ID
     * @return 结果
     */
    @Override
    public Result deleteProduct(Integer productId) {
// 验证产品ID
        if (productId == null) {
            return Result.error("产品ID不能为空");
        }

        // 检查产品是否存在
        Product existingProduct = this.getById(productId);
        if (existingProduct == null) {
            return Result.error("产品不存在");
        }

        boolean result = this.removeById(productId);
        if (result) {
            return Result.success(null, "删除产品成功");
        } else {
            return Result.error("删除产品失败");
        }
    }

    /**
     * 更新产品信息
     * @param product 产品信息
     * @return 结果
     */
    @Override
    public Result updateProduct(Product product) {
        if (product.getProductId()==null){
            return Result.error("产品id不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        Product findProduct=this.getById(product.getProductId());
        if (findProduct==null){
            return Result.error("产品不存在");
        }

        product.setUpdateTime(new Date());

       boolean result= this.updateById(product);

       if (result){
           return Result.success(product,"更新成功");
       }else {
           return Result.error("更新失败");
       }

    }

    @Override
    public Result findProductById(Integer productId) {
        if (productId==null){
            return  Result.error("产品id不能为空",ErrorCode.PARAM_EMPTY.getCode());
        }
        Product product = this.getById(productId);
        Double averageRating = productReviewsMapper.getAverageRating(productId);
        Integer count = productReviewsMapper.getReviewCount(productId);

        Map<String, Object> productMap = new HashMap<>();
        productMap.put("averageRating",averageRating);
        productMap.put("product",product);
        productMap.put("reviewCount",count);
        return Result.success(productMap);
    }

    /**
     * 分页查询产品列表
     */
    @Override
    public Page<Product> getProductPage(Page<Product> page, String price,String category,String search) {
        // 创建查询条件
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();

        // 添加筛选条件
        if (StringUtils.hasText(category)) {
            queryWrapper.eq(Product::getCategory, category);//分类
        }
        if (StringUtils.hasText(price)) {
            queryWrapper.lt(Product::getPrice, price);//小于此价格
        }
        if (StringUtils.hasText(search)){
            queryWrapper.like(Product::getProductName, search)
                    .or()
                    .like(Product::getEnglishName, search)
                    .or()
                    .like(Product::getDescription, search)
                    .or()
                    .like(Product::getScenarios, search)
                    .or()
                    .like(Product::getTags, search)
                    .orderByDesc(Product::getCreateTime);
        }
        // 按注册时间降序排序
        queryWrapper.orderByDesc(Product::getCreateTime);

        // 执行分页查询
        return page(page, queryWrapper);
    }




    /**
     * 模糊搜索产品
     */
    @Override
    public Page<Product> search(Page<Product> page, String keyword) {
        if (!StringUtils.hasText(keyword)) {
            return new Page<>(page.getCurrent(), page.getSize());
        }

        // 创建查询条件
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<Product>()
                .like(Product::getProductName, keyword)
                .or()
                .like(Product::getEnglishName, keyword)
                .or()
                .like(Product::getDescription, keyword)
                .or()
                .like(Product::getScenarios, keyword)
                .or()
                .like(Product::getTags, keyword)
                .orderByDesc(Product::getCreateTime);

        // 执行分页查询
        return this.page(page, wrapper);
    }

}
